package rrs;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Calendar;
import java.sql.*;



public class TransactionManager {
	public ArrayList<TransactItem> transactItemList = new ArrayList<TransactItem>();
	public String receiptId = ""; 
	public String transactType = ""; //changed into logD
	public String date = "";
	private TransactItem tranItem = null;
	private InventoryItem inventoryItem = null;
	public String viewScreenMsg = "";
	Connection conn;
	
	//Constructor
	public TransactionManager()
	{
		conn = DBInterface.dbConnOpen();
		receiptId = getReceiptId();	
		
//		date= String.valueOf(Calendar.DAY_OF_MONTH) + "/" + String.valueOf(Calendar.MONTH) + 
//				"/" + String.valueOf(Calendar.YEAR);
		System.out.println(date);
	}
	
	public boolean addPurchase(String productId, Integer quantity)
	{		
		String blanks = "                               ";		
		getInventoryItem(productId);
		if(inventoryItem == null)
		{
			viewScreenMsg += "There is no productId in the inventory!\n";
			return false;
		}
		else
		{
			if (inventoryItem.getQuantity() == 0)
			{
				viewScreenMsg += "Sorry, this product is out of stock..\n";
				return false;
			}				
			else if (inventoryItem.getQuantity() < quantity)
			{
				viewScreenMsg += "We only have maximum quantity less than your order in stock..\n";
				return false;
			}				
			else
			{
				transactType = "Purchase"; //Changed into LogD
				tranItem = new TransactItem();
				tranItem.setDescription(inventoryItem.getDescription());
				tranItem.setProductId(inventoryItem.getProductId());
				tranItem.setProductName(inventoryItem.getName());
				tranItem.setPurchasedPrice(inventoryItem.getPrice());
				tranItem.setQuantity(quantity);
				tranItem.setReceiptId(this.receiptId);
				tranItem.setTransactionType(transactType); //changed into logD
				
				//Add transacted Item into transactItemList
				transactItemList.add(tranItem.clone());
				
				double totalPrice = (double)(tranItem.getPurchasedPrice() * (double)tranItem.getQuantity());
				viewScreenMsg += tranItem.getDescription() + blanks.substring(0, 31 - tranItem.getDescription().length()) + "\t" +
								tranItem.getPurchasedPrice() + blanks.substring(0, 11 - String.valueOf(tranItem.getPurchasedPrice()).length()) + "\t" +
								String.valueOf(quantity) + blanks.substring(0, 11 - String.valueOf(quantity).length()) + "\t" + 
								"+" + String.valueOf(totalPrice) + blanks.substring(0, 11 - String.valueOf(totalPrice).length()) + "\n";
				
				tranItem = null;
				inventoryItem = null;
				
				return true;
			}
		}
	}
	
	public boolean addReturn(String productId, int quantity, String receiptId)
	{		
		String blanks = "                               ";		
		getPastTranItem(productId, receiptId);
		if (tranItem == null)
		{
			viewScreenMsg += "This past transaction does not exist!\n";
			return false;
		}
		else
		{
			if (quantity > tranItem.getQuantity())
			{
				viewScreenMsg += "The quantity you bought is less than the return quantity\n";
				transactType = "Fraudulent";
				TransactItem fraudulent = new TransactItem();
				fraudulent.setDescription(tranItem.getDescription());
				fraudulent.setProductId(tranItem.getProductId());
				fraudulent.setProductName(tranItem.getProductName());
				fraudulent.setPurchasedPrice(tranItem.getPurchasedPrice());
				fraudulent.setQuantity(quantity);
				fraudulent.setReceiptId(receiptId);
				fraudulent.setTransactionType(transactType);
				
				transactItemList.add(fraudulent);				
				return false;
			}
			else
			{
				transactType = "Return";
				tranItem.setTransactionType(transactType);
				tranItem.setQuantity(quantity);
				tranItem.setReceiptId(receiptId);
				transactItemList.add(tranItem.clone());
				
				double totalPrice = (double)(tranItem.getPurchasedPrice() * (double)tranItem.getQuantity());
				viewScreenMsg += tranItem.getDescription() + blanks.substring(0, 31 - tranItem.getDescription().length()) + "\t" +
								tranItem.getPurchasedPrice() + blanks.substring(0, 11 - String.valueOf(tranItem.getPurchasedPrice()).length()) + "\t" +
								String.valueOf(quantity) + blanks.substring(0, 11 - String.valueOf(quantity).length()) + "\t" + 
								"-" + String.valueOf(totalPrice) + blanks.substring(0, 11 - String.valueOf(totalPrice).length()) + "\n";

				tranItem = null;				
				return true;
			}			
		}
	}
	
	public boolean completeTran(String receiptId)
	{
		boolean rtn = false; 
		boolean hasFraudulent = false; boolean hasPurchase = false; boolean hasReturn = false;
		
		for(TransactItem t : transactItemList)
		{	
			if (t.getTransactionType() == "Fraudulent" && !hasFraudulent)
			{
				hasFraudulent = true; 
				rtn = rtn & insertTransaction(this.receiptId, t.getTransactionType(), date);
			}
			if (t.getTransactionType() == "Purchase" && !hasPurchase)
			{
				hasPurchase = true; 
				rtn = rtn & insertTransaction(this.receiptId, t.getTransactionType(), date);
			}
			if (t.getTransactionType() == "Return" && !hasReturn)
			{
				hasReturn = true; 
				rtn = rtn & insertTransaction(this.receiptId, t.getTransactionType(), date);	
				updateTransactItem(t.getProductId(), t.getReceiptId(), t.getQuantity());
			}
			
			rtn = rtn & insertTransactionItem(t.getProductId(), this.receiptId, t.getQuantity(), t.getPurchasedPrice(), 
					t.getDescription());
			
			updateInventory(t.getProductId(), t.getQuantity(), t.getTransactionType());
			this.viewScreenMsg = "";
		}
		
		long newReceipt = Long.parseLong(this.receiptId);
		newReceipt ++;
		this.receiptId = String.valueOf(newReceipt);
		return rtn;		
	}
	
	public String printReceipt()
	{
		String viewScreenMsg = "";
		String blanks = "                                     ";
		double balance = 0.0;
		
		for(TransactItem t : transactItemList)
		{
			if (t.getTransactionType() == "Purchase")
			{
				double totalPrice = (double)(tranItem.getPurchasedPrice() * (double)tranItem.getQuantity());
				viewScreenMsg += tranItem.getDescription() + blanks.substring(0, 21 - tranItem.getDescription().length()) + "\t" +
								tranItem.getPurchasedPrice() + blanks.substring(0, 21 - String.valueOf(tranItem.getPurchasedPrice()).length()) + "\t" +
								tranItem.getQuantity() + blanks.substring(0, 21 - String.valueOf(tranItem.getQuantity()).length()) + "\t" + 
								"+" + String.valueOf(totalPrice) + blanks.substring(0, 21 - String.valueOf(totalPrice).length()) + "\n";
				balance += totalPrice;
			}				
			if (t.getTransactionType() == "Return")
			{
				double totalPrice = (double)(tranItem.getPurchasedPrice() * (double)tranItem.getQuantity());
				viewScreenMsg += tranItem.getDescription() + blanks.substring(0, 21 - tranItem.getDescription().length()) + "\t" +
								tranItem.getPurchasedPrice() + blanks.substring(0, 21 - String.valueOf(tranItem.getPurchasedPrice()).length()) + "\t" +
								tranItem.getQuantity() + blanks.substring(0, 21 - String.valueOf(tranItem.getQuantity()).length()) + "\t" + 
								"-" + String.valueOf(totalPrice) + blanks.substring(0, 21 - String.valueOf(totalPrice).length()) + "\n";
				balance -= totalPrice;
			}				
			if (t.getTransactionType() == "Fraudulent")
			{
				viewScreenMsg += tranItem.getDescription() + blanks.substring(0, 21 - tranItem.getDescription().length()) + "\t" +
							     tranItem.getPurchasedPrice() + blanks.substring(0, 21 - String.valueOf(tranItem.getPurchasedPrice()).length()) + "\t" +
							     tranItem.getQuantity() + blanks.substring(0, 21 - String.valueOf(tranItem.getQuantity()).length()) + 
								"fraudulent return\n";
			}		
			
		}
		
		viewScreenMsg += "Total balance : " + String.valueOf(balance);
		
		return viewScreenMsg;
	}
	
	private boolean insertTransaction(String receiptId, String transactType, String date)
	{
		boolean rtn = false;
		try {
			Statement stmt = conn.createStatement();
			stmt.executeQuery("INSERT INTO Transaction VALUES('" + receiptId + "', '" +
					transactType + "', " + "CURRENT_DATE" + ")");
			
			stmt.close();
			rtn = true;
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			rtn = false;
		}		
		return rtn;
	}
	
	private boolean insertTransactionItem(String productId, String receiptId, int quantity, double purchasedPrice, 
			String description)
	{
		boolean rtn = false;
		try {
			Statement stmt = conn.createStatement();
			stmt.executeQuery("INSERT INTO TransactionItem VALUES('" + productId + "', '" + receiptId + "', " + purchasedPrice + ", " + quantity
					+ ", '" + description + "')");
			
			stmt.close();
			rtn = true;
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			rtn = false;
		}		
		return rtn;
	}
	
	private boolean updateInventory(String productId, int quantity, String transactType)
	{
		boolean rtn = false;
		try {
			Statement stmt = conn.createStatement();
			if (transactType == "Return")
			{
				stmt.executeQuery("UPDATE Inventory SET quantity = quantity + " + quantity + " where productId ='" + productId + "'");				
			}
			else if (transactType == "Purchase")
			{
				stmt.executeQuery("UPDATE Inventory SET quantity = quantity - " + quantity + " where productId ='" + productId + "'");		
			}
			
			stmt.close();
			rtn = true;
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			rtn = false;
		}		
		return rtn;
	}
	private boolean updateTransactItem(String productId, String receiptId, int quantity)
	{
		boolean rtn = false;
		try {
			Statement stmt = conn.createStatement();
			stmt.executeQuery("UPDATE TRANSACTIONITEM SET quantity = quantity - " + quantity + " where productId ='" + productId + 
						"' and RECEIPTID='" + receiptId + "'");				
						
			stmt.close();
			rtn = true;
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			rtn = false;
		}		
		return rtn;
	}
	private String getReceiptId()
	{
		String rtn = "";
		try {
			Statement stmt = conn.createStatement();
			ResultSet set = stmt.executeQuery("SELECT RECEIPTID FROM TRANSACTION");
			long lastId = 0; long id = 0;
			while(set!=null & set.next())
			{			
				id = Long.parseLong(set.getString(1));
				if (lastId<id)
					lastId = id;
			}
			lastId ++;
			rtn = String.valueOf(lastId);
			stmt.close();
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
//			e.printStackTrace(); //changed LOGD
			rtn = e.getMessage();
		}
		
		return rtn;
	}
	
	private InventoryItem getInventoryItem(String productId)
	{		
		try {
			Statement stmt;
			stmt = conn.createStatement();
			ResultSet set = stmt.executeQuery("select price, quantity, description from Inventory" + 
					" where productID = '" + productId + "'");
			
			if (set.next())
			{
				inventoryItem = new InventoryItem();
				inventoryItem.setPrice(Double.parseDouble(set.getString(1)));
				inventoryItem.setProductId(productId);
				inventoryItem.setQuantity(Integer.parseInt(set.getString(2)));				
				inventoryItem.setDescription(set.getString(3));
			}
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return inventoryItem;
	}
	
	//Get 
	private TransactItem getPastTranItem(String productId, String receiptId)
	{
		try {
			Statement stmt;
			stmt = conn.createStatement();
			ResultSet set1 = stmt.executeQuery("select a.quantity, a.purchasedPrice, a.description from TransactionItem a, Transaction b" + 
					" where a.productID = '" + productId + "' and a.receiptID = '" + receiptId + "' and b.receiptID='" + receiptId + 
					"' and b.TransactionType ='Purchase'");
			
			if (set1.next())
			{
				tranItem = new TransactItem();
				tranItem.setQuantity(Integer.parseInt(set1.getString(1)));
				tranItem.setPurchasedPrice(Double.parseDouble(set1.getString(2)));
				tranItem.setDescription(set1.getString(3));
				tranItem.setProductId(productId);
				tranItem.setReceiptId(receiptId);
			}			
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println(e.getMessage());
		}
		return tranItem;
	}	
}
